package com.lamda.zhekou.utils;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.jms.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URI;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;


/**
 * Http请求工具
 */
public class HttpUtils {

    /**
     * 无效的HTTP响应码
     */
    public static final int INVALID_HTTP_STATUS_CODE = -1;


    public static String get( String url) throws Exception {
        return get(url,null);
    }

    /**
     * @param httpClient
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String get(HttpClient httpClient, String url, List<NameValuePair> params) throws Exception {


        String body = null;
        // Get请求
        HttpGet httpget = new HttpGet(url);

        // 设置参数
        URI uri = new URI(httpget.getURI().toString());
        if (params != null) {
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
            uri = new URI(httpget.getURI().toString() + "?" + str);
        }

        httpget.setURI(uri);

        // 发送请求
        HttpResponse httpresponse = httpClient.execute(httpget);

        // 获取返回数据
        HttpEntity entity = httpresponse.getEntity();

        body = EntityUtils.toString(entity);

        EntityUtils.consume(entity);

        httpget.releaseConnection();

        return body;

    }


    public static String get(String url, List<NameValuePair> params) throws Exception {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpClient httpClient = httpClientBuilder.build();
        return get(httpClient, url, params);
    }


    public static String post(String url, List<NameValuePair> params) throws Exception {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpClient httpClient = httpClientBuilder.build();
        return post(httpClient, url, params);
    }

    /**
     * @param httpClient
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(HttpClient httpClient, String url, List<NameValuePair> params) throws Exception {

        String body = null;

        // Post请求

        HttpPost httppost = new HttpPost(url);
        // 设置参数
        URI uri = new URI(httppost.getURI().toString());
        if (params != null) {
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
            uri = new URI(httppost.getURI().toString() + "?" + str);
        }

        httppost.setURI(uri);
        // 发送请求

        HttpResponse httpresponse = httpClient.execute(httppost);

        // 获取返回数据

        HttpEntity entity = httpresponse.getEntity();

        body = EntityUtils.toString(entity);

        EntityUtils.consume(entity);

        httppost.releaseConnection();

        return body;

    }


    public static HttpResponse getReturnHttpResponse(String url, List<NameValuePair> params) throws Exception {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpClient httpClient = httpClientBuilder.build();

        return getByReturnHttpResponse(httpClient, url, params);
    }


    public static HttpResponse getByReturnHttpResponse(HttpClient httpClient, String url, List<NameValuePair> params) throws Exception {

        // Get请求
        HttpGet httpget = new HttpGet(url);

        // 设置参数
        URI uri = new URI(httpget.getURI().toString());
        if (params != null) {
            String str = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
            uri = new URI(httpget.getURI().toString() + "?" + str);
        }

        httpget.setURI(uri);

        // 发送请求
        HttpResponse httpresponse = httpClient.execute(httpget);
        httpget.releaseConnection();
        return httpresponse;
    }

    public static void consumeHttpHttpEntity(HttpEntity httpEntity) {
        try {
            EntityUtils.consume(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  Session session;
    public static   MessageProducer producer;
    public static Connection connection = null;

    public static void connectMq(){
        // ConnectionFactory ：连接工厂，JMS 用它创建连接
        ConnectionFactory connectionFactory;
        // Connection ：JMS 客户端到JMS Provider 的连接
        //Connection connection = null;
        // Session： 一个发送或接收消息的线程
       // Session session;
        // Destination ：消息的目的地;消息发送给谁.
        Destination destination;
        // MessageProducer：消息发送者
        //MessageProducer producer;
        // TextMessage message;
        // 构造ConnectionFactory实例对象，此处采用ActiveMq的实现jar
        connectionFactory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                "tcp://120.25.146.202:61616");
        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createSession(Boolean.TRUE,
                    Session.AUTO_ACKNOWLEDGE);
            // 获取session注意参数值xingbo.xu-queue是一个服务器的queue，须在在ActiveMq的console配置
            String localIp = getLocalIP();
            destination = session.createQueue("VPS"+localIp);
            // 得到消息生成者【发送者】
            producer = session.createProducer(destination);
            // 设置不持久化，此处学习，实际根据项目决定
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            // 构造消息，此处写死，项目就是参数，或者方法获取
//            sendMessage(session, producer);
//            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void sendMessage(Double total) {
        try {
            connectMq();
            TextMessage message = session.createTextMessage(new Date() +"  当前总收益:"+total);
            producer.send(message);
            session.commit();
        }catch (Exception e){

        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    /**
     * 获取本机ip地址，并自动区分Windows还是linux操作系统
     * @return String
     */
    public static String getLocalIP(){
        String sIP = "";
        InetAddress ip = null;
        try {
            //如果是Windows操作系统
            if(1==2){
                ip = InetAddress.getLocalHost();
            }
            //如果是Linux操作系统
            else{
                boolean bFindIP = false;
                Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                        .getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    if(bFindIP){
                        break;
                    }
                    NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                    //----------特定情况，可以考虑用ni.getName判断
                    //遍历所有ip
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = (InetAddress) ips.nextElement();
                        if( ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress()   //127.开头的都是lookback地址
                                && ip.getHostAddress().indexOf(":")==-1){
                            bFindIP = true;
                            break;
                        }
                    }

                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        if(null != ip){
            sIP = ip.getHostAddress();
        }
        return sIP;
    }
}
